package study.itheima.stusys;

import org.apache.commons.beanutils.BeanUtils;
import study.itheima.bean.Stu;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Map;

@WebServlet(value = "/AddStu",initParams = {})
public class AddStu extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Stu stu = new Stu();
        req.setCharacterEncoding("UTF-8");
        Map<String, String[]> map = req.getParameterMap();
        try {
            BeanUtils.populate(stu,map);
        } catch (Exception e) {
            e.printStackTrace();
        }
        BufferedWriter bw = new BufferedWriter(new FileWriter("e:\\stu.txt",true));
        bw.write(stu.toString());
        bw.newLine();
        bw.close();
        resp.setContentType("Text/Html;charset=UTF-8");
        PrintWriter pw = resp.getWriter();
        pw.write("添加成功,两秒后自动跳转...");
        String contextPath = req.getContextPath();
        //设置响应消息头定时刷新
        resp.setHeader("Refresh","2;URL="+ contextPath +"/webstu/index.jsp");
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
